package com.hantanger.weblog.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.hantanger.weblog.dao.UserDao;
import com.hantanger.weblog.model.User;
import com.hantanger.weblog.util.ClassFactory;
import com.hantanger.weblog.util.DaoHelper;
import com.hantanger.weblog.util.UserHelper;

public class CommonFilter implements Filter {
	
	private UserDao getUserDao(){
		return ClassFactory.getInstance(UserDao.class);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		try {
			HttpServletRequest httpRequest = (HttpServletRequest)request;
			String thisURL = httpRequest.getRequestURI();
			request.setAttribute("requestURL", thisURL);
			String visitorIP = httpRequest.getRemoteAddr();
			
			HttpSession session = httpRequest.getSession();
			String userEmail = (String)session.getAttribute("userEmail");
			User user = null;
			if(userEmail != null){
				user = getUserDao().getUserByEmail(userEmail);
				if(user == null){
					session.setAttribute("userEmail", null);
				}
			}
			UserHelper.setUserInfo(user, visitorIP);
			
			request.setAttribute("isAdmin", UserHelper.isAdmin());
			request.setAttribute("currentUser", UserHelper.getCurrentUser());
			request.setAttribute("isLogined", UserHelper.isLogined());
			request.setAttribute("isOnlineEnv", UserHelper.isOnlineEnv());
			
			chain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			UserHelper.setUserInfo(null,null);
			DaoHelper.getObjectify().clear();
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
	
	@Override
	public void destroy() {
	}

}
